package com.xuexiang.xuidemo.fragment.components.textview.supertextview;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tencent.mmkv.MMKV;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xuidemo.R;
import com.xuexiang.xuidemo.adapter.FlowTagAdapter;
import com.xuexiang.xuidemo.base.BaseFragment;
import com.xuexiang.xuidemo.utils.update.OkHttpUpdateHttpServiceImpl;
import com.xuexiang.xupdate.proxy.IUpdateHttpService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 *
 *
 * @author xuexiang
 * @since 2020/5/13 8:32 PM
 */
@Page(name = "库存-药品详情")
public class SuperKCClickFragment extends BaseFragment {

    @BindView(R.id.nameT)
    TextView name;
    @BindView(R.id.jwhT)
    TextView jwhT;
    @BindView(R.id.djbhT)
    TextView djbhT;
    @BindView(R.id.spidT)
    TextView spidT;
    @BindView(R.id.pihaoT)
    TextView pihaoT;
    @BindView(R.id.shpggT)
    TextView shpggT;
    @BindView(R.id.shengccjT)
    TextView shengccjT;
    @BindView(R.id.ZtotalNum)
    EditText ZtotalNum;
    @BindView(R.id.LtotalNum)
    EditText LtotalNum;

    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.Znum)
    EditText Znum;
    @BindView(R.id.Lnum)
    EditText Lnum;

    private String baozhuang = "大包装";

    // 弹框
    private Boolean isDialogShowing  = false;

    @BindView(R.id.flowlayout_single_select)
    FlowTagLayout mSingleFlowTagLayout;

//    @BindView(R.id.edt_rich_text)
//    MultiLineEditText richText;

    private List<String> list = new ArrayList<>();
    private int editTextCount = 0;  // 当前 EditText 数量
    private Boolean isContains = false;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_kc_super_click;
    }

    @Override
    protected void initViews() {
        Bundle arguments = getArguments();
        String string = arguments.getString("josnStr");
        JSONObject entries = JSONUtil.parseObj(string);

        name.setText(String.valueOf(entries.get("spmch")).trim());
        djbhT.setText(String.valueOf(entries.get("spbh")).trim());
        jwhT.setText(String.valueOf(entries.get("jwh")).trim());
        spidT.setText(String.valueOf(entries.get("spid")).trim());
        pihaoT.setText(String.valueOf(entries.get("pihao2")).trim());
        shpggT.setText(String.valueOf(entries.get("shpgg")).trim());
        shengccjT.setText(String.valueOf(entries.get("shpchd")).trim());

        FlowTagAdapter tagAdapter = new FlowTagAdapter(getContext());
        mSingleFlowTagLayout.setAdapter(tagAdapter);
        mSingleFlowTagLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        mSingleFlowTagLayout.setOnTagSelectListener((parent, position, selectedList) -> {
            baozhuang = getSelectedText(parent, selectedList);
        });
        tagAdapter.addTags(ResUtils.getStringArray(getContext(), R.array.tags_bz_values));

        int baozhshl = (int)Double.parseDouble(String.valueOf(entries.get("baozhshl")));
        int lingsshl = (int)Double.parseDouble(String.valueOf(entries.get("lingsshl")));
        if (baozhshl != 0  && lingsshl != 0) {
            int count = baozhshl + lingsshl;
            // 大小包装都不等于0 代表有大有小
            ZtotalNum.setText(String.valueOf(baozhshl));
            LtotalNum.setText(String.valueOf(lingsshl));
            tagAdapter.setSelectedPositions(0);
        }else {
            if (baozhshl != 0){
                // 代表是大包装
                ZtotalNum.setText(String.valueOf(baozhshl));
                LtotalNum.setText(String.valueOf(0));
                tagAdapter.setSelectedPositions(0);
            }else {
                // 代表是小包装
                LtotalNum.setText(String.valueOf(lingsshl));
                ZtotalNum.setText(String.valueOf(0));
                tagAdapter.setSelectedPositions(1);
                baozhuang = "小包装";
            }
        }

        // 添加第一个输入框
        addNewEditText();
    }

    private String getSelectedText(FlowTagLayout parent, List<Integer> selectedList) {
        StringBuilder sb = new StringBuilder("");
        for (int index : selectedList) {
            sb.append(parent.getAdapter().getItem(index));
        }
        return sb.toString();
    }

    /**
     * 增加条码输入框
     */
    private void addNewEditText() {
        if (editTextCount >= Integer.parseInt(ZtotalNum.getText().toString())+Integer.parseInt(LtotalNum.getText().toString())) {
            return; // 达到最大输入框数量，不再添加
        }

        LinearLayout linearLayout = new LinearLayout(getContext());
        TextView textView = new TextView(getContext());
        textView.setText(baozhuang+"：");
        linearLayout.addView(textView);

        // 创建新的 EditText
        EditText editText = new EditText(getContext());
        editText.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        editText.setGravity(Gravity.START);  // 设置文本从左侧对齐
        editText.setHint("条码");
        editText.setOnKeyListener((v, keyCode, event) -> {
            // 检查是否是回车键
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                // 执行你想在回车按下时做的事情
                String string = editText.getText().toString();
                if (StrUtil.isNotEmpty(string) && list.size() < Integer.parseInt(ZtotalNum.getText().toString())+Integer.parseInt(LtotalNum.getText().toString())) {
                    isContains = null;
                    boolean contains = false;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                        contains = list.stream().anyMatch(s -> s.contains(string));
                    }
                    isContains = contains;
                    if (isContains) {
                        // 扫码时候，如果当前记录重复了（不查历史记录，只查当前页面条码），弹出提示，是--继续扫码，否--清空当前行内容，等待重新扫码
                        if (!isDialogShowing){
                            isDialogShowing = true;
                            new MaterialDialog.Builder(getContext())
                                    .content(R.string.tip_repeat)
                                    .positiveText(R.string.lab_yes)
                                    .onPositive((dialog, which) -> {
                                        dialog.dismiss();
                                        list.add(baozhuang+"："+string);
                                        if (baozhuang.contains("大包装")){
                                            Znum.setText(list.size()+"");
                                        }else  {
                                            Lnum.setText(list.size()+"");
                                        }

                                        // 禁用输入框
                                        editText.setKeyListener(null);

                                        isDialogShowing = false;
                                        isContains = false;

                                        // 当输入框有内容并且尚未达到最大数量时，新增一个输入框
                                        addNewEditText();
                                    })
                                    .negativeText(R.string.lab_no)
                                    .onNegative((dialog, which) -> {
                                        dialog.dismiss();
                                        editText.setText("");
                                        editText.setSelection(editText.getText().length());
                                        XToastUtils.toast("清除成功");
                                        isDialogShowing = false;
                                    })
                                    .cancelable(false)
                                    .show();
                        }
                    }else {
                        list.add(baozhuang+"："+string);
                        if (baozhuang.contains("大包装")){
                            Znum.setText(list.size()+"");
                        }else  {
                            Lnum.setText(list.size()+"");
                        }

                        // 禁用输入框
                        editText.setKeyListener(null);

                        // 当输入框有内容并且尚未达到最大数量时，新增一个输入框
                        addNewEditText();
                    }
                }

                // 返回 true 表示事件已被处理，不再传递给其他控件
                return true;
            }
            return false; // 返回 false 让事件继续传递
        });

        // 增加数值变化监听
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                // 这个方法在文本变化后调用
                String inputText = editable.toString().trim();  // 获取输入的文本并去掉两端空格

                // 如果输入值为 "1"，执行相应操作
                if ("1".equals(inputText)) {
                    list.add(baozhuang+"：1");
                    if (baozhuang.contains("大包装")){
                        Znum.setText(list.size()+"");
                    }else  {
                        Lnum.setText(list.size()+"");
                    }

                    // 禁用输入框
                    editText.setKeyListener(null);

                    // 当输入框有内容并且尚未达到最大数量时，新增一个输入框
                    addNewEditText();
                }
            }
        });

        editText.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 长按清除内容
                new MaterialDialog.Builder(getContext())
                        .content(R.string.tip_del)
                        .positiveText("确认")
                        .negativeText("取消")
                        .onPositive((dialog, which) -> {
                            // 清除
                            String string = editText.getText().toString();
                            list.remove(baozhuang+"："+string);
                            editText.getText().clear();
                            XToastUtils.toast("清除成功");
                            editText.setKeyListener(TextKeyListener.getInstance());
                        })
                        .show();


                return false;

            }
        });

        if (!isContains){
            // 将新的 EditText 添加到容器中
//            container.addView(editText);
            linearLayout.addView(editText);
            container.addView(linearLayout);

            // 将光标聚焦到新的 EditText
            editText.requestFocus();

            // 更新当前的 EditText 数量
            editTextCount++;
        }
    }

    @OnClick(R.id.save)
    public void save() {
        if (list.size() < Integer.parseInt(ZtotalNum.getText().toString())+Integer.parseInt(LtotalNum.getText().toString())){
            // 当前录入数量小于总数量，是否还要继续提交？
            new MaterialDialog.Builder(getContext())
                    .content(R.string.tip_enter)
                    .positiveText("确认")
                    .negativeText("取消")
                    .onPositive((dialog, which) -> {
                        // 继续保存
                        saveSuperviseCodes();
                    })
                    .show();
        }else {
            // 直接保存
            saveSuperviseCodes();
        }
    }

    /**
     * 保存监管码
     */
    public void saveSuperviseCodes(){
        ArrayList<JSONObject> superviseCodes = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).contains("包装：")) {
                XToastUtils.toast("数据不合规：请选择包装，再扫码");
                return;
            }
            String[] split = list.get(i).split("：");
            JSONObject josn = new JSONObject();
            josn.set("djbh",djbhT.getText().toString()); // 单据编号
            josn.set("spid",spidT.getText().toString()); // 内部编码
            josn.set("pihao",pihaoT.getText().toString()); // 批号
            if (split[0].equals("大包装")){
                josn.set("dzjgm_type","2"); // 包装类型
            }else {
                josn.set("dzjgm_type","1"); // 包装类型
            }
            josn.set("djgm",split[1]); // 电子监管码
            josn.set("dzyname","admin"); // 仓库管理员
            superviseCodes.add(josn);
        }

        // 获取数据okhttp
        OkHttpUpdateHttpServiceImpl httpService = new OkHttpUpdateHttpServiceImpl();
        HashMap<String, Object> map = new HashMap<>();
        map.put("superviseCodes", superviseCodes);
//        String base_url = ResUtils.getString(getContext(), R.string.base_url);
        String base_url = MMKV.defaultMMKV().decodeString("BASE_URL");
        httpService.asyncPost(base_url+"/api/warehouse/kcSave", map, new IUpdateHttpService.Callback(){
                    @Override
                    public void onSuccess(String s) {
                        XToastUtils.toast("保存成功");
//                        // 返回上一页
//                        Intent intent = new Intent();
//                        intent.putExtra("refresh", true);  // 设置标志位，表示需要刷新
//                        getActivity().setResult(200, intent);  // 设置返回结果
//                        getActivity().onBackPressed();  // 调用返回上一页
//                        getActivity().finish();

//                        openPage(COddGoodsFragment.class,"code","200");

                        Intent resultIntent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putString("200","200");
                        resultIntent.putExtras(bundle);
                        setFragmentResult(RESULT_OK, resultIntent);
                        popToBack();
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        XToastUtils.toast("保存失败");

                    }
                }
        );
    }


    @Override
    protected void initListeners() {

    }

}
